var express = require("express");
var router = express.Router();
const policyModel = require("../../models/policyModel");

// 获取首页助农政策数据
router.get("/", (req, res) => {
  policyModel
    .find()
    .select({ __v: 0 })
    .sort({ time: -1 })
    .limit(6)
    .then((data) => {
      data.forEach((item) => {
        item.time = item.time.split(" ")[0];
      });
      return res.json({
        code: 200,
        data: data,
        msg: "获取政策信息成功",
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 获取全部助农政策信息
router.get("/info", (req, res) => {
  let { pageNo, pageSize } = req.query;
  policyModel
    .find()
    .then((result) => {
      if (result.length === 0) {
        return res.json({
          code: 200,
          msg: "政策数据为空",
          data: null,
        });
      } else {
        policyModel
          .find()
          .select({ _v: 0 })
          .sort({ time: -1 })
          .skip((pageNo - 1) * pageSize)
          .limit(pageSize)
          .then((data) => {
            let total = result.length;
            data.forEach((item) => {
              item.time = item.time.split(" ")[0];
            });
            return res.json({
              code: 200,
              msg: "获取政策信息成功",
              data: data,
              total: total,
            });
          })
          .catch((err) => {
            return res.json({
              code: "1001",
              msg: "数据库读取失败~~~",
              data: null,
            });
          });
      }
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~",
        data: null,
      });
    });
});

// 根据id获取数据
router.get("/:id", (req, res) => {
  let { id } = req.params;
  policyModel
    .findOne({ _id: id })
    .select({ __v: 0 })
    .then((data) => {
      return res.json({
        code: 200,
        data: data,
        msg: "获取资讯信息成功",
      });
    })
    .catch((err) => {
        console.log(err);
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

module.exports = router;
